<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Upload, User, Loading, Delete, Picture } from '@element-plus/icons-vue'
import { getStudentInfo, updateStudentInfo, uploadImage } from '@/api/student'

const form = ref({
    id: null,
    account: '',
    name: '',
    phone: '',
    email: '',
    gender: null,
    avatar: ''
})

const loading = ref(false)
const editMode = ref(false)
const uploadLoading = ref(false)

const genderOptions = [
    { value: 1, label: '男' },
    { value: 2, label: '女' }
]

const loadStudentInfo = () => {
    loading.value = true
    getStudentInfo().then(res => {
        if (res.data) {
            form.value = { ...res.data }
        }
    }).catch(() => {
        ElMessage.error('获取个人信息失败')
    }).finally(() => {
        loading.value = false
    })
}

const handleEdit = () => {
    editMode.value = true
}

const handleSave = () => {
    if (!form.value.name) {
        ElMessage.error('请输入姓名')
        return
    }
    if (!form.value.phone) {
        ElMessage.error('请输入手机号')
        return
    }
    if (!form.value.email) {
        ElMessage.error('请输入邮箱')
        return
    }
    if (!form.value.gender) {
        ElMessage.error('请选择性别')
        return
    }

    loading.value = true
    updateStudentInfo(form.value).then(res => {
        ElMessage.success('更新成功')
        editMode.value = false
        // 更新本地存储的学生信息
        const studentInfo = JSON.parse(localStorage.getItem('studentInfo') || '{}')
        studentInfo.name = form.value.name
        studentInfo.avatar = form.value.avatar
        localStorage.setItem('studentInfo', JSON.stringify(studentInfo))
    }).catch(() => {
        ElMessage.error('更新失败')
    }).finally(() => {
        loading.value = false
    })
}

const handleCancel = () => {
    editMode.value = false
    loadStudentInfo()
}

const handleAvatarUpload = (file) => {
    const isImage = file.type.startsWith('image/')
    if (!isImage) {
        ElMessage.error('只能上传图片文件!')
        return false
    }

    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!')
        return false
    }

    uploadLoading.value = true
    uploadImage(file).then(res => {
        form.value.avatar = res.data
        ElMessage.success('头像上传成功')
    }).catch(() => {
        ElMessage.error('头像上传失败')
    }).finally(() => {
        uploadLoading.value = false
    })

    return false // 阻止自动上传
}

const handleImageError = () => {
    console.warn('头像图片加载失败:', form.value.avatar)
    ElMessage.warning('头像图片加载失败，请重新上传')
    // 可以选择清空无效的头像URL
    // form.value.avatar = ''
}


onMounted(() => {
    loadStudentInfo()
})
</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header" style="display: flex; justify-content: space-between; align-items: center;">
                <span>基本资料</span>
                <div v-if="!editMode">
                    <el-button type="primary" @click="handleEdit">编辑</el-button>
                </div>
                <div v-else>
                    <el-button type="success" @click="handleSave" :loading="loading">保存</el-button>
                    <el-button @click="handleCancel">取消</el-button>
                </div>
            </div>
        </template>

        <el-form :model="form" label-width="100px" style="max-width: 600px;" :disabled="!editMode">
            <el-form-item label="账号">
                <el-input v-model="form.account" disabled />
            </el-form-item>

            <el-form-item label="姓名" required>
                <el-input v-model="form.name" placeholder="请输入姓名" />
            </el-form-item>

            <el-form-item label="手机号" required>
                <el-input v-model="form.phone" placeholder="请输入手机号" />
            </el-form-item>

            <el-form-item label="邮箱" required>
                <el-input v-model="form.email" placeholder="请输入邮箱" />
            </el-form-item>

            <el-form-item label="性别" required>
                <el-select v-model="form.gender" placeholder="请选择性别" style="width: 100%;">
                    <el-option v-for="option in genderOptions" :key="option.value" :label="option.label"
                        :value="option.value" />
                </el-select>
            </el-form-item>

            <el-form-item label="头像">
                <div class="avatar-container">
                    <el-upload :show-file-list="false" :before-upload="handleAvatarUpload"
                        :disabled="!editMode || uploadLoading" accept="image/*" class="avatar-upload">
                        <div class="avatar-display" :class="{ 'editable': editMode, 'uploading': uploadLoading }">
                            <div v-if="form.avatar" class="avatar-image">
                                <el-image :src="form.avatar" fit="cover" :preview-src-list="[form.avatar]"
                                    @error="handleImageError">
                                    <template #error>
                                        <div class="image-error">
                                            <el-icon class="error-icon">
                                                <Picture />
                                            </el-icon>
                                            <span class="error-text">加载失败</span>
                                        </div>
                                    </template>
                                </el-image>
                                <div v-if="editMode" class="avatar-overlay">
                                    <el-icon class="upload-icon">
                                        <Upload />
                                    </el-icon>
                                    <span class="upload-text">点击更换</span>
                                </div>
                            </div>
                            <div v-else class="avatar-placeholder">
                                <el-icon class="placeholder-icon">
                                    <User />
                                </el-icon>
                                <span class="placeholder-text">暂无头像</span>
                                <div v-if="editMode" class="upload-hint">点击上传</div>
                            </div>
                            <div v-if="uploadLoading" class="upload-loading">
                                <el-icon class="loading-icon">
                                    <Loading />
                                </el-icon>
                                <span>上传中...</span>
                            </div>
                        </div>
                    </el-upload>
                    <div v-if="form.avatar && editMode" class="avatar-actions">
                        <el-button type="danger" size="small" circle @click="form.avatar = ''">
                            <el-icon>
                                <Delete />
                            </el-icon>
                        </el-button>
                    </div>
                </div>
                <div v-if="editMode" class="upload-tips">
                    支持 JPG、PNG、JPEG、GIF 格式，文件大小不超过 2MB
                </div>
            </el-form-item>
        </el-form>
    </el-card>
</template>

<style scoped>
.page-container {
    margin: 20px;
}

.avatar-container {
    display: flex;
    align-items: flex-start;
    gap: 16px;
}

.avatar-upload {
    display: inline-block;
}

.avatar-display {
    width: 120px;
    height: 120px;
    border: 2px dashed #dcdfe6;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    overflow: hidden;
    cursor: pointer;
    transition: all 0.3s ease;
}

.avatar-display.editable:hover {
    border-color: #409eff;
    background-color: #f5f7fa;
}

.avatar-display.uploading {
    border-color: #409eff;
    background-color: #f0f9ff;
}

.avatar-image {
    width: 100%;
    height: 100%;
    position: relative;
}

.avatar-image .el-image {
    width: 100%;
    height: 100%;
    border-radius: 50%;
}

.avatar-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    color: white;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s ease;
    border-radius: 50%;
}

.avatar-display.editable:hover .avatar-overlay {
    opacity: 1;
}

.upload-icon {
    font-size: 24px;
    margin-bottom: 4px;
}

.upload-text {
    font-size: 12px;
}

.avatar-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #909399;
    text-align: center;
}

.placeholder-icon {
    font-size: 48px;
    margin-bottom: 8px;
}

.placeholder-text {
    font-size: 14px;
    margin-bottom: 4px;
}

.upload-hint {
    font-size: 12px;
    color: #409eff;
}

.upload-loading {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(255, 255, 255, 0.9);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #409eff;
    border-radius: 50%;
}

.loading-icon {
    font-size: 24px;
    margin-bottom: 4px;
    animation: rotate 1s linear infinite;
}

@keyframes rotate {
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(360deg);
    }
}

.avatar-actions {
    display: flex;
    align-items: flex-start;
    padding-top: 8px;
}

.upload-tips {
    color: #909399;
    font-size: 12px;
    margin-top: 8px;
    margin-left: 136px;
}

.image-error {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: #f56c6c;
    background-color: #fef0f0;
    border-radius: 50%;
}

.error-icon {
    font-size: 32px;
    margin-bottom: 4px;
}

.error-text {
    font-size: 12px;
}
</style>